//
//  CustomActionSheet.swift
//  ezyform
//
//  Created by MoennigQ on 12/6/20.
//  Copyright © 2020 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SnapKit
//定义全局变量，类似于OC中的宏定义：#define
let Screen_Width = UIScreen.main.bounds.size.width//屏幕宽
let Screen_Height = UIScreen.main.bounds.size.height//屏幕高
let Space_Line:CGFloat = 16//间隔
class CustomActionSheet: UIView,UITableViewDelegate,UITableViewDataSource {
    
    /*---------------如果需要自定义绘图，请执行这个方法
     // Only override draw() if you perform custom drawing.
     // An empty implementation adversely affects performance during animation.
     override func draw(_ rect: CGRect) {
     // Drawing code
     }
     */
    
    //创建相关控件
    var maskV = UIView()//半透明背景
    var tableView = UITableView()//表格
    var cellArray = [CellModel]()//表格数组
    var cancelModel = CellModel()//取消标题设置
    //标题头视图
    var headView: ContentLabel = {
        let headerLabel = ContentLabel(hexStr: "#292D3266")
        headerLabel.text = R.string.localizable.pleaseSelectASignatureMode()
        headerLabel.backgroundColor = .white
        headerLabel.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        headerLabel.textAlignment = .center
        headerLabel.frame = CGRect(x: 0, y: 0, width: APPConfig.WidthForPortrait, height: 50)
        return headerLabel
    }()
    
    var selectedClosure:((Int) -> ())?//选中单元格closure
    var cancelClosure:(() -> ())?//取消单元格closure
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //初始化方法:参数一：头视图，参数二：表格数组，参数三：取消的标题设置，参数四：选择单元格closure，参数五：取消closure
    
    init(title: String,aCellArray:[CellModel],aCancelModel:CellModel,aSelectedClosure:@escaping ((Int) -> ()),aCancelClosure: (() -> ())?) {
        super.init(frame: headView.frame)
        headView.text = title
        cellArray = aCellArray
        cancelModel = aCancelModel
        selectedClosure = aSelectedClosure
        cancelClosure = aCancelClosure
        
        //创建UI视图
        self.createUI()
        
    }
    //MARK: ------------ 创建UI视图
    func createUI() {
        self.frame = UIScreen.main.bounds
        //半透明背景
        maskV = UIView.init(frame: UIScreen.main.bounds)
        maskV.backgroundColor = UIColor.black
        maskV.alpha = 0.5
        maskV.isUserInteractionEnabled = true
        self.addSubview(maskV)
        
        //表格
        tableView = UITableView.init(frame: CGRect.zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.layer.cornerRadius = Constant.BackViewCornerRadius
        tableView.clipsToBounds = true
        tableView.rowHeight = 50.0
        tableView.bounces = false
        tableView.backgroundColor = UIColor.clear
        tableView.tableHeaderView = self.headView
        tableView.separatorStyle = .none
        
        //注册单元格:+ (Class)class OBJC_SWIFT_UNAVAILABLE("use 'aClass.self' instead");
        tableView.register(ActionSheetTableViewCell.self, forCellReuseIdentifier: ActionSheetTableViewCell.reuseCellIdentifier)
        self.addSubview(tableView)
    }
    //MARK:------------ UITableViewDelegate,UITableViewDataSource
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (section == 0) ? cellArray.count:1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: ActionSheetTableViewCell = tableView.dequeueReusableCell(withIdentifier: ActionSheetTableViewCell.reuseCellIdentifier) as! ActionSheetTableViewCell
        if indexPath.section == 0 {
            if indexPath.row == cellArray.count-1 {
                //添加贝塞尔曲线，设计边角样式UIBezierPath与CAShapeLayer
                //注意：Swift中的“或”加了一个rawValue：UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
                let maskPath = UIBezierPath.init(roundedRect: CGRect.init(x: 0, y: 0, width: Screen_Width - Space_Line*2, height: tableView.rowHeight), byRoundingCorners: UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue), cornerRadii: CGSize.init(width: 10, height: 10))
                let maskLayer = CAShapeLayer.init()
                maskLayer.frame = (cell.contentView.bounds)
                maskLayer.path = maskPath.cgPath
                cell.layer.mask = maskLayer
            }
            cell.setData(self.cellArray[indexPath.row])
        }else{
            cell.setData(self.cancelModel,cancelRowFlag: true)
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if (selectedClosure != nil) {
                selectedClosure!(Int(indexPath.row))
            }
        }else{
            if (cancelClosure != nil) {
                cancelClosure!()
            }
        }
        
        self.dismiss()
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return Space_Line
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.bounds.size.width, height: Space_Line))
        footerView.backgroundColor = UIColor.clear
        return footerView
    }
    //MARK:------绘制视图
    override func layoutSubviews() {
        super.layoutSubviews()
        self.show()
    }
    //滑动弹出
    func show() {
        tableView.frame = CGRect.init(x: Space_Line, y: Screen_Height, width: Screen_Width-Space_Line * 2, height: tableView.rowHeight * CGFloat(cellArray.count + 1) + headView.bounds.size.height + Space_Line * 2)
        UIView.animate(withDuration: 0.2) {
            var rect:CGRect = self.tableView.frame
            rect.origin.y -= (self.tableView.bounds.size.height + 10)
            self.tableView.frame = rect
        }
    }
    //滑动消失
    func dismiss() {
        UIView.animate(withDuration: 0.2, animations: {
            var rect:CGRect = self.tableView.frame
            rect.origin.y += self.tableView.bounds.size.height
            self.tableView.frame = rect
        }) { (finished) in
            self.removeFromSuperview()
        }
    }
    //MARK:------触摸屏幕其他位置谈下
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.dismiss()
    }
}
class CellModel: NSObject{
    var imageName: String = ""
    var title: String = ""
    var value: String = ""
    override init() {
        super.init()
    }
    init(title: String, imageName: String = "", value: String = "") {
        self.title = title
        self.value = value
        self.imageName = imageName
    }
}
import SnapKit
class ActionSheetTableViewCell: UITableViewCell{
    
    let operImageView = UIImageView()
    let operTitleLabel = ContentLabel(R.font.interMedium(size: 15))
    var operImageViewWidthConstrains: Constraint!
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        self.backgroundColor = .clear
        self.contentView.backgroundColor = .white
        //top的line view
        let lineView = View(frame: CGRect(x: Space_Line, y: 0, width: APPConfig.WidthForPortrait - Space_Line * 4, height: 1))
        self.contentView.addSubview(lineView)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    func setUpviewsWithoutImage(){
        //title
        let toplineView = View(hexStr: "#F5F5F5")
        self.contentView.addSubview(toplineView)
        toplineView.snp.makeConstraints({ (make) in
            make.top.equalToSuperview()
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(1)
        })
        self.contentView.addSubview(operTitleLabel)
        operTitleLabel.snp.makeConstraints({ (make) in
            make.center.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        })
    }
    func setUpviewsWithImage(){
        //
        let toplineView = View(hexStr: "#F5F5F5")
        self.contentView.addSubview(toplineView)
        toplineView.snp.makeConstraints({ (make) in
            make.top.equalToSuperview()
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(1)
        })
        //backview
        let backView = UIView()
        backView.backgroundColor = .clear
        self.contentView.addSubview(backView)
        backView.snp.makeConstraints { (make) in
            make.top.bottom.centerX.equalToSuperview()
            make.width.equalTo(140)
        }
        //image view
        backView.addSubview(operImageView)
        operImageView.snp.makeConstraints({ (make) in
            make.left.centerY.equalToSuperview()
            make.height.width.equalTo(24)
        })
        //title
        operTitleLabel.setFont(R.font.sfProTextRegular(size: 15))
        backView.addSubview(operTitleLabel)
        operTitleLabel.snp.makeConstraints({ (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(operImageView.snp.right).offset(12)
            make.height.width.greaterThanOrEqualTo(0)
        })
        //
    }
    func setData(_ model: CellModel,cancelRowFlag: Bool = false){
        //image
        if model.imageName != ""  {
            self.operImageView.image = UIImage(named: model.imageName)
            self.setUpviewsWithImage()
        }else{
            self.operImageView.image = nil
            self.setUpviewsWithoutImage()
        }
        //title
        self.operTitleLabel.text = model.title
        if cancelRowFlag {
            self.contentView.drawCorner(byRoundingCorners: [.allCorners])
        }
    }
}
